package com.yikes.yygh.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.RandomUtil;
import com.yikes.yygh.common.enums.ResultCodeEnum;
import com.yikes.yygh.config.AlibabaSmsConfiguration;
import com.yikes.yygh.redis.constant.SmsConstant;
import com.yikes.yygh.service.SmsCodeService;
import com.yikes.yygh.web.utils.As;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @Author: guanrong.yin
 * @Date: 2024/12/17 14:54
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsCodeServiceImpl implements SmsCodeService {

    private final RedisTemplate redisTemplate;

    private final AlibabaSmsConfiguration smsConfiguration;

//    private final UserInfoClient userInfoClient;

    @Override
    public void sendSmsCode(String phone) {

//        boolean result = (boolean) userInfoClient.checkMobile(phone).getData();
//        As.isTure(!result, ResultCodeEnum.MOBILE_NOT_REGISTERED);

        // 生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 获取 redis 缓存中的数据
        String phoneCode = (String) redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PREFIX + phone);
        if (CharSequenceUtil.isNotBlank(phoneCode)) {
            As.throwEx(ResultCodeEnum.SMS_LIMIT_CONTROL_ERROR);
        }

        // 发送短信
        smsConfiguration.sendSmsCode(phone, code);

        // 验证码-缓存到 redis 中
        redisTemplate.opsForValue().set(SmsConstant.SMS_CODE_PREFIX + phone, code,
                SmsConstant.NUMERAL_MINUTE, TimeUnit.MINUTES);

    }
}
